﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Common;
using Common.Admin;
using Common.Controls;
using Liquid;
using System.Windows.Browser;
using System.IO;

namespace SLAdmin.UserControls
{
    public partial class EditStudy : UserControl
    {
        Guid _studyId;
        Study _study;
        App _myApp;
        StudyManager _studyManager = StudyManager.GetInstance();
        StudyDataClient _studyDataClient = new StudyDataClient();
        DialogHelper _dialogHelper = new DialogHelper();

        public EditStudy()
        {
            InitializeComponent();
        }
        public delegate void StudyUpdatedDelegate();
        public event StudyUpdatedDelegate StudyUpdated;
        public EditStudy(Study SelectedStudy)
        {
            InitializeComponent();
            this.DataContext = SelectedStudy;
            _study = SelectedStudy;
            _studyId = _study.StudyId;
            BindConditions();
            BindStudyWaves();            
            try
            {                
                _studyDataClient.CreateConditionCompleted += new StudyDataClient.CreateConditionCompletedDelegate(_myApp_CreateConditionCompleted);
                _studyDataClient.CreateWaveCompleted += new StudyDataClient.CreateWaveCompletedDelegate(_myApp_CreateWaveCompleted);
                _studyDataClient.DeleteConditionCompleted += new StudyDataClient.DeleteConditionCompletedDelegate(_myApp_DeleteConditionCompleted);
                _studyDataClient.DeleteStudyWaveCompleted += new StudyDataClient.DeleteStudyWaveCompletedDelegate(_myApp_DeleteStudyWaveCompleted);
                _dialogHelper.DialogAccepted += new DialogHelper.DialogAcceptedDelegate(_myApp_DialogAccepted);
                _studyDataClient.DeleteAllStudyDataEvent += new StudyDataClient.DeleteAllStudyDataDelegate(_myApp_DeleteAllStudyDataEvent);
                _studyDataClient.StudyDataLoadedEvent += new StudyDataClient.StudyDataLoadedDelegate(_myApp_StudyDataLoadedEvent);
                _studyDataClient.DeleteIndividualStudyResultsCompleted += new StudyDataClient.DeleteIndividualStudyResultsCompletedDelegate(_myApp_DeleteIndividualStudyResultsCompleted);
            }            
            catch { }
            BindClaims();
        }

        private void BindClaims()
        {
            List<Claim> ClaimsAddedList = new List<Claim>();
            List<Claim> ClaimsNotAddedList = new List<Claim>();
            _studyDataClient.GetClaims(_studyId, out ClaimsAddedList, out ClaimsNotAddedList);
            ClaimsAdded.ItemsSource = ClaimsAddedList;
            ClaimsNotAdded.ItemsSource = ClaimsNotAddedList;
        }
        void _myApp_DeleteIndividualStudyResultsCompleted()
        {
            BindStudyResults();
        }

        void _myApp_StudyDataLoadedEvent(List<StudyResultsIndividualEmail> Results)
        {
            ParticpantGrid.ItemsSource = null;
            ParticpantGrid.DataContext = null;
            ParticpantGrid.ItemsSource = Results;
            ParticpantGrid.DataContext = Results;            
        }

        void _myApp_DeleteAllStudyDataEvent()
        {
            BindStudyResults();
        }

        void _myApp_DialogAccepted(object DataContext)
        {
            if (DataContext is Condition)
            {
                _studyDataClient.DeleteCondition(DataContext as Condition);
            }
            else if (DataContext is StudyWave)
            {
                _studyDataClient.DeleteStudyWave(DataContext as StudyWave);
            }
            else if (DataContext is Study)
            {
                _studyDataClient.DeleteAllStudyData((DataContext as Study).StudyId);                
            }
            else if (DataContext is StudyResultsIndividualEmail)
            {
                _studyDataClient.DeleteIndividualStudyResults(_studyId, (DataContext as StudyResultsIndividualEmail).IndividualId);                
            }
        }

        void _myApp_DeleteStudyWaveCompleted(StudyWave DeletedWave )
        {
            StudyWaveGrid.SelectedItem = null;
            List<StudyWave> Waves = StudyWaveGrid.ItemsSource as List<StudyWave>;
            Waves.Remove(DeletedWave);
            StudyWaveGrid.ItemsSource = null;
            StudyWaveGrid.ItemsSource = Waves;
            StudyUpdated();
        }

        void _myApp_DeleteConditionCompleted(Condition DeletedCondition)
        {
            ConditionGrid.SelectedItem = null;
            List<Condition> Conditions = ConditionGrid.ItemsSource as List<Condition>;
            Conditions.Remove(DeletedCondition);
            ConditionGrid.ItemsSource = null;
            ConditionGrid.ItemsSource = Conditions;
            StudyUpdated();
        }

        void _myApp_CreateWaveCompleted(StudyWave StudyWave)
        {
            StudyWaveGrid.SelectedItem = null;
            List<StudyWave> Waves = StudyWaveGrid.ItemsSource as List<StudyWave>;
            Waves.Add(StudyWave);
            StudyWaveGrid.ItemsSource = null;
            StudyWaveGrid.ItemsSource = Waves;
            StudyUpdated();
        }

        void _myApp_CreateConditionCompleted(Condition Condition)
        {
            ConditionGrid.SelectedItem = null;
            List<Condition> Conditions = ConditionGrid.ItemsSource as List<Condition>;
            Conditions.Add(Condition);
            ConditionGrid.ItemsSource = null;
            ConditionGrid.ItemsSource = Conditions;
            StudyUpdated(); 
        }

        private void BindConditions()
        {
            ConditionGrid.ItemsSource = _studyDataClient.GetConditions(_studyId);            
        }
        private void BindStudyWaves()
        {
            StudyWaveGrid.ItemsSource = _studyDataClient.GetStudyWaves(_studyId);
        }
        private void BindResources()
        {
            AdminServiceWCFClient a = StudyManager.GetAdminServiceWCFClient();
            a.GetResourcesForStudyIdCompleted += new EventHandler<GetResourcesForStudyIdCompletedEventArgs>(delegate(object sender, GetResourcesForStudyIdCompletedEventArgs e)
            {
                ResourcesGrid.ItemsSource = e.Result;
            });
            a.GetResourcesForStudyIdAsync(_studyId);
        }
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            Study myStudy = this.DataContext as Study;
            List<Condition> Conditions = ConditionGrid.ItemsSource as List<Condition>;
            List<StudyWave> StudyWaves = StudyWaveGrid.ItemsSource as List<StudyWave>;
            _studyDataClient.UpdateStudy(myStudy);
            foreach (Condition c in Conditions)
            {
                _studyDataClient.UpdateCondition(c);
            }
            foreach (StudyWave sw in StudyWaves)
            {
                _studyDataClient.UpdateStudyWave(sw);
            }
            List<Claim> ClaimsAddedList = ClaimsAdded.ItemsSource as List<Claim>;
            _studyDataClient.UpdateClaimsForStudy(_studyId, ClaimsAddedList);
            StudyUpdated();
        }

        private void btnConditionDelete_Click(object sender, RoutedEventArgs e)
        {
            Button myButton = sender as Button;            
            _dialogHelper.Alert("Confirm Delete", "Are you sure you want to delete this condition?",myButton.DataContext,LayoutRoot);
         }
         

        private void btnStudyWaveDelete_Click(object sender, RoutedEventArgs e)
        {
            Button myButton = sender as Button;
            _dialogHelper.Alert("Confirm Delete", "Are you sure you want to delete this wave?", myButton.DataContext,LayoutRoot);
        }

        private void btnNewWave_Click(object sender, RoutedEventArgs e)
        {            
            _studyDataClient.CreateWave(_studyId);            
        }

        private void btnNewCondition_Click(object sender, RoutedEventArgs e)
        {
            _studyDataClient.CreateCondition(_studyId);
        }

        private void btnDeleteAll_Click(object sender, RoutedEventArgs e)
        {
            Button myButton = sender as Button;
            _dialogHelper.Alert("Confirm Delete", "Are you sure you want to delete ALL data from this study?", myButton.DataContext,LayoutRoot);            
        }

        private void StudyTabs_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems[0].Equals(tabParticipant))
            {
                BindStudyResults();
            }
            else if (e.AddedItems[0].Equals(tabResources))
            {
                BindResources();
            }
        }
        private void BindStudyResults()
        {
            //The Participant Tab is selected            
            _studyDataClient.GetStudyData(_studyId);
        }
        private void btnDeleteIndividualResult_Click(object sender, RoutedEventArgs e)
        {
            Button myButton = sender as Button;
            _dialogHelper.Alert("Confirm Delete", "Are you sure you want to delete the data for this individual?", myButton.DataContext,LayoutRoot);            
        }

        private void btnExportToExcel_Click(object sender, RoutedEventArgs e)
        {
#if (DEBUG)
            Uri SourceUri = new Uri(
                ConfigurationSettings.DownloadDataUrl_local + "?" +
                ConfigurationSettings.DownloadDataQueryStringName + "=" + _studyId.ToString(), UriKind.Relative);
#else
             Uri SourceUri = new Uri(
                ConfigurationSettings.DownloadDataUrl + "?" +
                ConfigurationSettings.DownloadDataQueryStringName + "=" + _studyId.ToString(), UriKind.Relative);
#endif
            HtmlPage.Window.Navigate(SourceUri, "_blank");
        }

        private void btnRun_Click(object sender, RoutedEventArgs e)
        {
            Uri SourceUri = new Uri(_study.StudyURL, UriKind.Absolute);
            HtmlPage.Window.Navigate(SourceUri, "_blank");
        }

        private void btnAddClaim_Click(object sender, RoutedEventArgs e)
        {
            if (ClaimsNotAdded.SelectedItem != null)
            {
                List<Claim> ClaimsAddedList = ClaimsAdded.ItemsSource as List<Claim>;
                List<Claim> ClaimsNotAddedList = ClaimsNotAdded.ItemsSource as List<Claim>;
                Claim myClaim = ClaimsNotAdded.SelectedItem as Claim;
                ClaimsNotAddedList.Remove(myClaim);
                ClaimsAddedList.Add(myClaim);
                ClaimsAdded.ItemsSource = null;
                ClaimsNotAdded.ItemsSource = null;
                ClaimsAdded.ItemsSource = ClaimsAddedList;
                ClaimsNotAdded.ItemsSource = ClaimsNotAddedList;
            }
        }

        private void btnRemoveClaim_Click(object sender, RoutedEventArgs e)
        {
            if (ClaimsAdded.SelectedItem != null)
            {
                List<Claim> ClaimsAddedList = ClaimsAdded.ItemsSource as List<Claim>;
                List<Claim> ClaimsNotAddedList = ClaimsNotAdded.ItemsSource as List<Claim>;
                Claim myClaim = ClaimsAdded.SelectedItem as Claim;
                ClaimsAddedList.Remove(myClaim);
                ClaimsNotAddedList.Add(myClaim);
                ClaimsAdded.ItemsSource = null;
                ClaimsNotAdded.ItemsSource = null;
                ClaimsAdded.ItemsSource = ClaimsAddedList;
                ClaimsNotAdded.ItemsSource = ClaimsNotAddedList;
            }
        }

        private void btnUploadFile_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Multiselect = true;
            ofd.Filter = "All files|*.*";
            if (ofd.ShowDialog().Value)
            {
                UploadFileHandler Uploader = new UploadFileHandler();
                foreach (FileInfo File in ofd.Files)
                {
                    Uploader.UploadFile(_studyId,File.Name, File.OpenRead());                    
                }
            }
        }

        private void btnDeleteResource_Click(object sender, RoutedEventArgs e)
        {
            string Path = (sender as Button).DataContext as string;
            AdminServiceWCFClient a = StudyManager.GetAdminServiceWCFClient();
            a.DeleteResourceCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(delegate(object sender1, System.ComponentModel.AsyncCompletedEventArgs e1)
            {
                BindResources();
            });
            a.DeleteResourceAsync(Path, _studyId);
        }

        //private void UserControl_LayoutUpdated(object sender, EventArgs e)
        //{
        //    StudyTabs.Width = this.ActualWidth;
        //}

       

    }
}
